package com.mall.rest.service.Impl;

import com.mall.mapper.TbItemCatMapper;
import com.mall.pojo.CatNode;
import com.mall.pojo.CatResult;
import com.mall.pojo.TbItemCat;
import com.mall.pojo.TbItemCatExample;
import com.mall.rest.service.ItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCatServiceImpl implements ItemCatService{

   @Autowired
   private TbItemCatMapper tbItemCatMapper;


    @Override
    public CatResult getItemCatList() {

        CatResult catResult = new CatResult();

        //查询分类列表
        catResult.setData(getCatList(0));
        return catResult;
    }


    private List<?> getCatList(long parentId){


        TbItemCatExample example=new TbItemCatExample();

        TbItemCatExample.Criteria criteria=example.createCriteria();
        criteria.andParentIdEqualTo(parentId);

        List<TbItemCat> list=tbItemCatMapper.selectByExample(example);

        List results=new ArrayList<>();

        int count=0;

        for (TbItemCat item:list) {
            if (item.getIsParent()) {
                CatNode temp = new CatNode();

                if (parentId == 0) {
                    temp.setName("<a href='/products/" + item.getId() + ".html'>"
                            + item.getName() + "</a>");
                } else {
                    temp.setName(item.getName());
                }

                temp.setUrl("<a href='/products/" + item.getId() + ".html'>" + item.getName() + "</a>");

                temp.setItem(getCatList(item.getId()));


                results.add(temp);
                count++;
                //第一层只取14条记录
                if(parentId == 0 && count>=14){
                    break;
                }

            } else {
                results.add("/products/" + item.getId() + ".html|" + item.getName());
            }
        }

        return results;
    }
}
